package com.fannuo.demo.Controller;

import com.fannuo.demo.Api.HadoopApi;
import com.fannuo.demo.Api.HbaseApi;
import com.fannuo.demo.Entity.Journal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("meta")
public class MetaController {
    @Autowired
    HadoopApi hadoopApi;
    @Autowired
    HbaseApi hbaseApi;

    // 导入元数据文件，即meta.json ,位于项目的meta目录中
    @GetMapping("putMeta")
    @ResponseBody
    public void putMeta() {
        String path = "meta/meta.json"; //meta.json文件所在路径
        hbaseApi.put(path);
    }
    // 导入pdf文件到hadoop中
    @GetMapping("putFiles")
    @ResponseBody
    public void putFiles() {
        String dir = "meta/pdf"; //pdf文件所在文件夹
        hadoopApi.putFiles(dir);
    }

    // 查看元数据信息
    @GetMapping("/list")
    public String list(Model model) {
        List<Journal> journalList = hbaseApi.getList(10);
        model.addAttribute(journalList);
        return "list"; // list.html
    }
    // 下载文件
    @GetMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response,String id) {
        if(id == null) {
            return;
        }
        byte[] bytes = hadoopApi.getFile(id);
        if(bytes != null) {
            try{
                response.reset();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length",String.valueOf(bytes.length));
                response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(id+".pdf", "UTF-8"));
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(bytes);
                outputStream.close();
            } catch (IOException e) {
//                e.printStackTrace();
            }
        }
    }

    //
}
